<!-- 
	交了钱钱的甲方爸爸才能用的客服系统 
	抠门的甲方只能用自动回复的垃圾客服 请移步 ->  /userPage/onlineService/webHttp
 -->
<template>
	<view class="page">
		<status-bar :title='title?title:"联系客服"'></status-bar>
		<view class="box">
			
			<!-- 布局 -->
			<view v-if='list && list.length > 0' class="catList" @click="showEmoji=false">
				<!-- 注释 -->
				<view class="DiLine" v-if='page > 1 && noMore'>---------没有更多了---------</view>
				<view v-for="(item, key) in list" :key="key" class="item">
					<view v-if="item.id == myID" class="right">
						
						<view class="msg-box">
							<view class="username">{{ item.username }}</view>
							<!-- 图片 -->
							<view class="img-box" v-if='item.content.indexOf("img[") > -1' @click="prevImg(item.content)">
								<image @error="item.content = staticUrl+'/imageLoading.png'" :src="imgUrl+item.content.replace('img[','').replace(']','')" mode="widthFix"></image>
							</view>
							<!-- 表情 -->
							<view class="face-box" v-else-if='item.content.indexOf("face[") > -1' v-html="rich(item.content)">
								<!-- <template v-for="(fa,f) in item.content.split(' ')">
									<image :src="staticUrl+'/face/'+fa.replace('face[','').replace(']','').trim()+'.gif'"></image>
								</template> -->
							</view>
							<view class="message-box" v-else>{{ item.content }}</view>
						</view>
						
						<view style="margin-left:10px;">
							<image class="avatar" @error='item.avatar=""' :src="item.avatar?item.avatar:staticUrl+'/youkeer.png'" />
						</view>
					</view>
					
					<view v-else class="left">
						<view>
							<image class="avatar" @error='item.avatar=""' :src="item.avatar?item.avatar:staticUrl+'/youkeer.png'" />
						</view>
						<view class="msg-box">
							<view class="username">{{ item.username }}</view>
							<view class="img-box" v-if='item.content.indexOf("img[") > -1' @click="prevImg(item.content)">
								<image :src="imgUrl+item.content.replace('img[','').replace(']','')" mode="widthFix"></image>
							</view>
							<!-- 有表情 -->
							<view class="face-box" v-else-if='item.content.indexOf("face[") > -1' v-html="rich(item.content)">
								<!-- <template v-for="(fa,f) in item.content.split(' ')">
									<image :src="staticUrl+'/face/'+fa.replace('face[','').replace(']','').trim()+'.gif'"></image>
								</template> -->
							</view>
							<view class="message-box" v-else>{{ item.content }}</view>
						</view>
					</view>
					
				</view>
			</view>
			
			
			<!-- 输入框 -->
			<view class="bottom-box" :class="{show1:showEmoji}">
				<view class="bottom">
					<view class="bottom-p">
						<view class="input-box">
							<input type="text" confirm-type="send" @confirm='clickRequest' placeholder="请输入你要发送的内容" cursor-spacing="50" v-model="value" @focus="focus" />
						</view>
						<view class="thmeBg send-btn" @tap="clickRequest" :style="{'--color': color}">发送</view>
						<!-- <text class="iconfont icon-zengjia thmeColor" :style="{'--color': color}" @click="showEmoji = true"></text> -->
					</view>
					
					
					<!-- 底部分类 -->
					<view class="classification">
						<view @click="camera">
							<image :src="staticUrl+'/icon/tupian.png'"></image>
						</view>
						<view @click="camera">
							<image :src="staticUrl+'/icon/xiangji.png'"></image>
						</view>
						<view @click="show">
							<image :src="staticUrl+'/icon/biaoqing.png'"></image>
						</view>
					</view>
					
					<view class="emoji-box" :style="{opacity:showEmoji?1:0}">
						<view class="title">表情</view>
						<view class="emoji">
							<image v-for="(fac,i) in face" :key='i' :src="staticUrl+'/face/'+fac+'.gif'" @click="checkEmoj(fac)"></image>					
						</view>
					</view>
					
					
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {mapState} from 'vuex';
	var ping = null,that;
	export default {
		data() {
			return {
				color: getApp().globalData.color,
				staticUrl: this.staticUrl,
				imgUrl: this.imgUrl,
				
				
				value: '',
				tableData: [],
				list: [],
				scrollTop: -1,
				myID: '', // 我
				mesage: {
					type: "chatMessage",
					data: {
						mine: {
							"username": "",
							"avatar": "",
							"id": '',
							"mine": true,
							"content": ""
						},
						to: {
							"username": "",
							"id": '',
							"avatar": "",
							"sign": '',
							"status": "",
							"name": "",
							"type": "friend"
						},
						token: ""
					}
				},
				start: true,
				hisID: '',
				page: 1,
				showEmoji: false, // 显示表情
				socketTask: null,
				face: ["微笑", "嘻嘻", "哈哈", "可爱", "可怜", "挖鼻", "吃惊", "害羞", "挤眼", "闭嘴", "鄙视", "爱你", "泪",
					"偷笑", "亲亲", "生病", "太开心", "白眼", "右哼哼", "左哼哼", "嘘", "衰", "委屈", "吐", "哈欠", "抱抱", "怒",
					"疑问", "馋嘴", "拜拜", "思考", "汗", "困", "睡", "钱", "失望", "酷", "色", "哼", "鼓掌", "晕", "悲伤",
					"抓狂", "黑线", "阴险", "怒骂", "互粉", "心", "伤心", "猪头", "熊猫", "兔子", "ok", "耶", "good", "NO",
					"赞", "来", "弱", "草泥马", "神马", "囧", "浮云", "给力", "围观", "威武", "奥特曼", "礼物", "钟", "话筒",
					"蜡烛", "蛋糕"
				],
				httpUrl: this.echatUrl,
				more: false,
				shop_id: 0,
				pageNum: 20,
				
				noMore:false,
				title: '联系客服',
				// title: uni.getStorageSync('startUp').title
			};
		},
		onLoad(e) {
			that = this;
			if(e.shop_id){
				that.shop_id = e.shop_id
			}
			this.closeSocket();
			this.connectSocketInit();
			this.$nextTick(()=> {
				setTimeout(()=>{
					that.goBottom()
				},1000)
			})
		},
		computed:{
			...mapState(['tabTitle','color','city','navHeight','System','vid','share','bid']),
			rich(text){
				return function(text){
					var reg = /face\[([^\[\]])*\]/g;
					var des = text.replace(reg,(ev)=>{
						ev = ev.replace("face[","").replace("]","")
						ev = "<span style='margin: 3px 0;width:22px;height:22px;display:inline-block;background:url("+this.staticUrl + "/face/"+ ev + ".gif);background-size: contain;vertical-align: middle;'></span>"
						return ' '+ev+' '
					});
					return des
				}
			},
			valueFilter(text){
				return function(text){
					var reg = /face\[([^\[\]])*\]/g;
					var des = text.replace(reg,(ev)=>{
						ev = ev.replace("face","")
						return ev
					});
					return des
				}
			}
		},
		onPageScroll(e) {
			if (e.scrollTop == 0 && this.more) {
				uni.createSelectorQuery().in(this).select(".box").boundingClientRect(function(data) {
					that.scrollTop = data.height
					that.getChatLog('des');
				}).exec()
			}
		},
		onUnload() {
			this.closeSocket();
		},
		beforeDestroy() {// 关闭socket
			this.closeSocket();
		},
		methods: {
			goBottom(){
				setTimeout(()=>{
					uni.pageScrollTo({
						duration: 0,
						scrollTop: 999999999
					})
				},200)
			},
			getChatLog(type) {// 获取历史
				that.more = false
				that.noMore = false
				uni.request({
					url: that.httpUrl + '/echat/User/chatLog',
					method: 'POST',
					data:{
						token: that.token,
						page: that.page,
						limit: that.pageNum,
						id: that.hisID, // 对方id 
					},
					dataType: "json",
					header: {
						'content-type': 'application/x-www-form-urlencoded',
					},
					success: function(res) {
						if(res.data.code == 0){
							let list = res.data.data.data
							if(list){
								if(type == 'rev'){ // 反序
									that.list = that.list.concat(list).reverse()
								}
								if(type == 'des'){ // 正序.reverse()
									that.list = list.concat(that.list)
									that.$nextTick(function(){
										uni.createSelectorQuery().in(this).select(".box").boundingClientRect(function(data) {
											uni.pageScrollTo({
												duration: 0,
												scrollTop: data.height - that.scrollTop
											})
										}).exec()
									})
								}
								if (list.length > that.pageNum-1) {
									that.more = true
									that.page ++
								}
							}
							if((!list || list.length < that.pageNum) && that.page > 1){
								that.noMore = true
							}
						}else{
							uni.showToast({
								icon:"none",
								title: res.data.msg,
								duration: 2000
							})
						}
					}
				})
			},
			
			
			connectSocketInit() {
				that.$http.get({
					url: '/singleSaleApi/getChatToken',
					data: {
						shop_id: that.shop_id, // 0：联系总平台 其他：联系店铺

					}
				}).then(res1 => {
					if(res1.code == 200){
						that.myID = res1.data.mine.id
						that.mesage.data = {
							mine: {
								"username": res1.data.mine.nickname,
								"avatar": res1.data.mine.avatar,
								"id": res1.data.mine.id,
								"mine": true,
								"content": ""
							},
							to: {
								"username": res1.data.to.nickname,
								"id": res1.data.to.id,
								"avatar": res1.data.to.avatar,
								"sign": res1.data.to.sign,
								"status": res1.data.to.status,
								"name": res1.data.to.name,
								"type": "friend"
							},
							token: res1.data.token
						}
						that.token = res1.data.token
						that.hisID = res1.data.to.id
						that.myname = res1.data.mine.nickname;
						let server = res1.data.server
						if(res1.store_name)
							that.title = res1.store_name;
						that.socketTask = uni.connectSocket({
							url: server + '//?token=' + res1.data.token,
							header: {
								'content-type': 'application/json'
							},
							method: 'GET',
							success() {
								uni.onSocketOpen(function(res) { // Socket连接已打开！
									that.getChatLog('rev');
									that.goBottom()
									uni.sendSocketMessage({
										data: 'ok',
										success: function() {
											uni.onSocketMessage(function(res1) {
												var ret = JSON.parse(res1.data);
												console.log("*******onSocketMessage*******")
												console.log(ret)
												if (ret.content && ret.offline != 1) { // 离线消息不push 不然消息记录重复
													that.list.push(ret);
													that.goBottom()
												}
											})
										}
									})
									ping = setInterval(function() {
										that.socketTask.send({
											data: 'ping',
											async success(back) {
												console.log("ping");
											}
										})
									}, 1000 * 10)
								})
							},
							fail(res2) {
								console.log(res2)
							}
						});
					}else{
						uni.showToast({
							icon:"none",
							title: res1.msg,
							duration:2000
						})
					}
				})
			},
			
			clickRequest() { // 发送
				if (this.value == '') {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '不能发送空白消息'
					});
				} else {
					var _self = this;
					let temp = _self.mesage
					temp.data.mine['content'] = this.value;
					var ok = JSON.stringify(temp);
					_self.socketTask.send({
						data: ok,
						async success() {
							console.log("消息发送成功");
							let mine = {
								"username": that.mesage.data.mine.username,
								"avatar": that.mesage.data.mine.avatar,
								"id": that.mesage.data.mine.id,
								"mine": true,
								"content": that.value
							}
							_self.list.push(mine)
							_self.value = ''
							that.goBottom()
							_self.socketTask.onMessage((res) => {
								console.log("收到服务器内容：" + res.data);
								that.goBottom()
							});
						}
					})
				}
			},
			checkEmoj(emoji) {
				emoji = "face[" + emoji + "] "
				that.value += emoji
			},
			focus() {
				that.showEmoji = false
				that.goBottom()
			},
			show() {
				that.goBottom()
				that.showEmoji = true
			},
			closeSocket() {
				uni.closeSocket(function(res) {
					console.log('WebSocket 已关闭！');
				});
			},
			camera() {
				var _self = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'],
					success: function(res) {
						uni.showLoading({
							title: ''
						})
						const uploadTask = uni.uploadFile({
							url: _self.baseUrl + '/zzjApp/uploadChatPic?bid='+ that.bid,
							filePath: res.tempFilePaths[0],
							name: 'file',
							dataType: "json",
							success: function(uploadFileRes) {
								uploadFileRes = JSON.parse(uploadFileRes.data)
								let ok = _self.mesage
								ok.data.mine['content'] = "img[" + uploadFileRes.data.src + "]"
								_self.socketTask.send({
									data: JSON.stringify(ok),
									async success() {
										console.log("消息发送成功");
										let mine = {
											"username": that.mesage.data.mine.username,
											"avatar": that.mesage.data.mine.avatar,
											"id": that.mesage.data.mine.id,
											"mine": true,
											"content": "img[" + uploadFileRes.data.src + "]"
										}
										_self.list.push(mine)
										that.goBottom()
									}
								})
							},
							fail: function(res) {
								uni.showToast({
									title:res.msg,
									icon:'none'
								})
							},
							complete: function() {
								uni.hideLoading();
							}
						})
					}
				});
			},
			prevImg(img) {
				var arry = this.imgUrl + img.replace('img[', '').replace(']', '')
				uni.previewImage({
					urls: [arry]
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		background-color: #FFFFFF;
		.box{
			.catList {
				box-sizing: border-box;
				padding: 0 20rpx;
				.item{
					padding-bottom: 30rpx;
					padding-top: 10rpx;
					.username {
						font-size: 26rpx;
						color: #999;
					}
					.avatar {
						width: 80rpx;
						height: 80rpx;
						border-radius: 50%;
						border: 1px solid #DDDDDD;
					}
					.message-box {
						border: 1px solid #EEEEEE;
						font-size: 26rpx;
						color: #232323;
						border-radius: 14rpx;
						margin-top: 10rpx;
						text-align: justify;
						padding: 10rpx 16rpx;
						display: inline-block;
					}
					.img-box {
						border: 1px solid #EEEEEE;
						margin-top: 10rpx;
						display: inline-block;
						border-radius: 14rpx;
						overflow: hidden;
						image {
							display: block;
							width: 300rpx;
						}
					}
					.face-box {
						border: 1px solid #EEEEEE;
						border-radius: 14rpx;
						margin-top: 10rpx;
						padding: 10rpx 16rpx;
						display: inline-block;
						image {
							display: inline-block;
							width: 44rpx;
							height: 44rpx;
							margin:0 6rpx 6rpx;
						}
					}
					.msg-box{
						max-width: 70%;
					}
					.left {
						display: flex;
						flex-wrap: nowrap;
						justify-content: flex-start;
						text-align: left;
						.message-box,.face-box{
							background: #f8f8f8;
						}
						.msg-box{
							margin-left:10px;
						}
					}
					.right {
						display: flex;
						flex-wrap: nowrap;
						justify-content: flex-end;
						text-align: right;
						.message-box,.face-box{
							background: #b0e5ff96;
						}
					}
				}
			}
			.bottom-box{
				height: 188rpx;
				box-sizing: content-box;
				padding-bottom: constant(safe-area-inset-bottom);
				padding-bottom: env(safe-area-inset-bottom);
				&.show1 {
					height: 610rpx;
					.bottom{
						height: 600rpx;
					}
				}
				.bottom {
					width: 100%;
					background: #f1f1f1;
					padding-top: 10px;
					position: fixed;
					left: 0;
					right: 0;
					bottom: 0;
					height: 174rpx;
					transition: all 0.2s;
					box-sizing: content-box;
					padding-bottom: constant(safe-area-inset-bottom);
					padding-bottom: env(safe-area-inset-bottom);
					.bottom-p {
						height: 74rpx;
						display: flex;
						flex-wrap: nowrap;
						padding: 0 20rpx;
						.icon-zengjia{
							font-size: 64rpx;
							padding-left: 20rpx;
						}
						.input-box{
							flex: 1;
							height: 100%;
							background-color: #ffffff;
							border-radius: 40px;
							display: flex;
							input {
								flex: 1;
								height: 100%;
								padding: 0 20rpx !important;
							}
						}
						.send-btn{
							width: 146rpx;
							font-size: 28rpx;
							text-align: center;
							line-height: 74rpx;
							border-radius: 40px;
							color: #ffffff;
							background: #25b0f3;
							margin-left: 20rpx;
						}
					}
					.classification {
						display: flex;
						flex-wrap: nowrap;
						margin: 0 auto;
						overflow: hidden;
						view {
							height: 100%;
							height: 78rpx;
							padding: 0 20rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							image {
								width: 40rpx;
								height: 40rpx;
							}
						}
					}
					.emoji-box {
						position: relative;
						z-index: 2;
						.title {
							padding: 0 20rpx;
						}
						.emoji {
							padding: 10rpx 0;
							height: 396rpx;
							box-sizing: border-box;
							overflow-y: auto;
							image {
								margin: 12rpx 0 12rpx 22rpx;
								width: 44rpx;
								height: 44rpx;
							}
						}
					}
				}
			}
		}
	}
</style>
